package cn.wolfcode.web.controller;


import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.feign.AlipayFeignApi;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;


@RestController
@RequestMapping("/orderPay")
@RefreshScope
public class OrderPayController {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Qualifier("cn.wolfcode.feign.AlipayFeignApi")
    @Autowired
    private AlipayFeignApi alipayFeignApi;

    /**
     * 支付流程
     *
     * @param orderNo
     * @param type
     * @param response
     * @return data为 form 表单字符串
     */
    @GetMapping("/alipay")
    public Result<String> alipay(String orderNo, int type, HttpServletResponse response) {
        // 1. 参数校验
        if (StringUtils.isEmpty(orderNo) || StringUtils.isEmpty(String.valueOf(type)))
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);

        // 2. 判断支付类型
        if (OrderInfo.PAYTYPE_ONLINE == type) {
            // 在线支付
            String formString = orderInfoService.payOnline(orderNo);
            return Result.success(formString);
        } else if (OrderInfo.PAYTYPE_INTERGRAL == type) {
            // 积分支付
            orderInfoService.payIntergral(orderNo);
        } else {
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }

        return Result.success("");
    }


    @Value("${pay.frontEndPayUrl}")
    private String frontEndPayUrl;

    /**
     * 同步回调 和 异步回调
     * @param params
     * @return
     */
    @RequestMapping("/return_url")
    public void returnUrl(@RequestParam Map<String, String> params, HttpServletResponse response) throws IOException {
        // 验签 (验证签名)
        Result<Boolean> result = alipayFeignApi.rsaCheck(params);

        if (result != null && !result.hasError()) {
            if (result.getData()) {
                String outTradeNo = params.get("out_trade_no");
                response.sendRedirect(frontEndPayUrl + outTradeNo);
                return;
            }
        }
        response.sendRedirect("http://localhost/50x.html");
    }
    @RequestMapping("/notify_url")
    public void notify_url(@RequestParam Map<String, String> params, HttpServletResponse response) throws IOException {
        // 验签 (验证签名)
        Result<Boolean> result = alipayFeignApi.rsaCheck(params);

        PrintWriter writer = response.getWriter();

        if (result != null && !result.hasError()) {
            if (result.getData()) {
                String outTradeNo = params.get("out_trade_no");
                // 修改订单状态
                orderInfoService.paySuccess(outTradeNo);
                writer.write("success");
            } else {
                writer.write("fail");
            }
        }
    }


    /**
     * 退款
     * @param orderNo
     * @return
     */
    @RequestMapping("/refund")
    public Result<String> refund(String orderNo) {
        // 1. 参数校验
        if (StringUtils.isEmpty(orderNo))
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);

        OrderInfo orderInfo = orderInfoService.find(orderNo);

        if (orderInfo.getPayType() == OrderInfo.PAYTYPE_ONLINE) {
            orderInfoService.refundOnline(orderInfo);
        } else if (orderInfo.getPayType() == OrderInfo.PAYTYPE_INTERGRAL) {
            orderInfoService.refundIntergral(orderInfo);
        } else {
            throw new BusinessException(SeckillCodeMsg.OPT_ERROR);
        }

        return Result.success("");
    }
}
